package com.rds.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.rds.common.core.text.Convert;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author rds
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 计算两个时间大小
     */
    public static Boolean getDateContrast(Date oldDate, Date nowDate)
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return oldDate.getTime() > nowDate.getTime();
    }

    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            smdate=sdf.parse(sdf.format(smdate));
            bdate=sdf.parse(sdf.format(bdate));
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24)+1;
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween1(Date smdate, Date bdate) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            smdate=sdf.parse(sdf.format(smdate));
            bdate=sdf.parse(sdf.format(bdate));
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }


    /**
     * 将日期转化为日期字符串。失败返回null。
     * @param date 日期
     * @return 日期字符串
     */
    public static String DateToString(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = format.format(date);
        return dateString;
    }

    /**
     * 日期转换成yyyy-MM-dd
     * @param dataStr
     * @return
     * @throws ParseException
     */
    public static String dateConversion(String dataStr) {
        SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        Date date =new Date();
        try {
            date = sdf.parse(dataStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String formatStr=new SimpleDateFormat("yyyy-MM-dd").format(date);
        return formatStr;
    }


    ///<summary>
    ///由秒数得到日期几天几小时几分几秒
    ///</summary
    ///<param name="t">秒数</param>
    ///<param name="type">0：转换后带秒，1:转换后不带秒</param>
    ///<returns>几天几小时几分几秒</returns>
    public static String parseTimeSeconds(int t, int type)
    {
        String r = "";
        int day, hour, minute, second;
        if (t >= 86400)  //天,
        {
            day = Convert.toInt(t / 86400);
            hour = Convert.toInt((t % 86400) / 3600);
            minute = Convert.toInt((t % 86400 % 3600) / 60);
            second = Convert.toInt(t % 86400 % 3600 % 60);
            if (type == 0)
                r = day + ("天") + hour + ("时") + minute + ("分") + second + ("秒");
            else
                r = day + ("天") + hour + ("时") + minute + ("分");

        }
        else if (t >= 3600) //时,
        {
            hour = Convert.toInt(t / 3600);
            minute = Convert.toInt((t % 3600) / 60);
            second = Convert.toInt(t % 3600 % 60);
            if (type == 0)
                r = hour + ("时") + minute + ("分") + second + ("秒");
            else
                r = hour + ("时") + minute + ("分");
        }
        else if (t >= 60) //分
        {
            minute = Convert.toInt(t / 60);
            second = Convert.toInt(t % 60);
            r = minute + ("分") + second + ("秒");
        }
        else
        {
            second = Convert.toInt(t);
            r = second + ("秒");
        }
        return r;
    }

    /**
     *
     * 计算两个时间相差多少小时
     * @param startDate 开始日期
     * @param endDate   结束时间
     */
    public static int getDifferHour(Date startDate, Date endDate) {
        long dayM = 1000 * 24 * 60 * 60;
        long hourM = 1000 * 60 * 60;
        long differ = endDate.getTime() - startDate.getTime();
        long hour = differ % dayM / hourM + 24 * (differ / dayM);
        return Integer.parseInt(String.valueOf(hour));
    }

    /**
     *日期格式验证
     * @param str string数据
     */
    public static boolean dateFormatValidation(String str){
        // 验证日期格式为YYYY-MM-DD的正则表达式为
        String regex = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
        boolean flag =str.matches(regex);
        //验证日期格式为DD/MM/YYYY的正则表达式为
        String regex2 = "(((0[1-9]|[12][0-9]|3[01])/((0[13578]|1[02]))|((0[1-9]|[12][0-9]|30)/(0[469]|11))|(0[1-9]|[1][0-9]|2[0-8])/(02))/([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3}))|(29/02/(([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00)))";
        if (flag){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 成将yyyy-mm-dd转换为mm/dd/yyyy 日期格式
     * @param currentDate
     * @return
     * @throws ParseException
     */
    public static String parse2PLMDate(String currentDate) throws Exception{
        Calendar cTarget = Calendar.getInstance();
        cTarget.setTimeInMillis(new SimpleDateFormat("yyyy-MM-dd").parse(currentDate).getTime());
        StringBuilder sbWhere = new StringBuilder();
        String sMinute  = String.valueOf(cTarget.get(Calendar.MINUTE));
        String sSecond  = String.valueOf(cTarget.get(Calendar.SECOND));
        String sAMPM    = (cTarget.get(Calendar.AM_PM) == 0 ) ? "AM" : "PM";
        if(sMinute.length() == 1) { sMinute = "0" + sMinute; }
        if(sSecond.length() == 1) { sSecond = "0" + sSecond; }
        sbWhere.append(cTarget.get(Calendar.MONTH) + 1).append("/").append(cTarget.get(Calendar.DAY_OF_MONTH)).append("/").append(cTarget.get(Calendar.YEAR));
        sbWhere.append(" ").append(cTarget.get(Calendar.HOUR)).append(":").append(sMinute).append(":").append(sSecond).append(" ").append(sAMPM);
        return sbWhere.toString();
    }

    /**
     * @description: TODO 转换PMS时间格式
     * @param: date PMS系统时间
     * @return: PLM系统能识别时间
     * @author: LiChuanlong
     * @date: 2022/7/30 18:10
     */
    public static String parse2PLMDate(Date date) throws Exception{
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        StringBuilder sbWhere = new StringBuilder();
        String sMinute  = String.valueOf(calendar.get(Calendar.MINUTE));
        String sSecond  = String.valueOf(calendar.get(Calendar.SECOND));
        String sAMPM    = (calendar.get(Calendar.AM_PM) == 0 ) ? "AM" : "PM";
        if(sMinute.length() == 1) { sMinute = "0" + sMinute; }
        if(sSecond.length() == 1) { sSecond = "0" + sSecond; }
        sbWhere.append(calendar.get(Calendar.MONTH) + 1).append("/").append(calendar.get(Calendar.DAY_OF_MONTH)).append("/").append(calendar.get(Calendar.YEAR));
        sbWhere.append(" ").append(calendar.get(Calendar.HOUR)).append(":").append(sMinute).append(":").append(sSecond).append(" ").append(sAMPM);
        return sbWhere.toString();
    }

    /**
     * 根据日期获取对应新期
     * @param: date 日期（yyyy-mm-dd）
     */
    public static String getWeekDays(String date){
        String[]weekDays = {
                "星期日",
                "星期一",
                "星期二",
                "星期三",
                "星期四",
                "星期五",
                "星期六"
        };
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            cal.setTime(sdf.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 将日期转化为日期字符串。失败返回null。
     * @param date 日期
     * @return 日期字符串
     */
    public static String DateToString(Date date,String dateFormat){
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        String dateString = format.format(date);
        return dateString;
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }
}
